<?php
// +----------------------------------------------------------------------
// | LIKE [ JUST DO IT ]
// +----------------------------------------------------------------------
// | Author: Mr.hu <huhaiyang7788@163.com>
// +----------------------------------------------------------------------
// | DESC: 
// +----------------------------------------------------------------------


namespace common\logs\mongo;


use common\controllers\Functions;
use yii\log\Target;

class MongoTarget extends Target
{

    public function export()
    {
        $mongo_log=(new MongoSave())->getCollection();
        $mongo_autoincrement=new Autoincrement();
        $insert_data['_id']=$mongo_autoincrement->incByTableName(MongoSave::$log_table_name,'_id');
        $insert_data['is_readed']=0;
        $parse_str=unserialize($this->getMessagePrefix(''));
        foreach ($this->messages as $message){
            list($text, $level, $category, $timestamp) = $message;
            $insert_data[]=[
                'level' => $level,
                'category' => $category,
                'message' => $text,
                'create_time' => $timestamp,
                'format_time'=>Functions::dateTime(),
            ];
        }
        $mongo_log->insert(array_merge($insert_data,$parse_str));
    }


    /**
     * 获取记录日记的前缀
     * @param $message
     * return void
     * @ Mr.hu.
     */
    public static function getPrefix($message=null)
    {
        $return['ip'] =\Yii::$app->request->getUserIP();//客户端的ip地址
        //用户的标识，如果是front，则表示bc_wx_user的主键id,如果是接口，则记录使用的token值
        //根据session是否存在来辨别是front的项目 ，还是接口的调用
        if(\Yii::$app->session->isActive){
            $return['app_type']='front';
            $return['bc_wx_uid']=\Yii::$app->session['user']['id'];
        }else{
            $return['app_type']='api';
            $return['token']=REQUEST_TOKEN;
        }
        return serialize($return);
    }





}